<template>
	<xn-form-container
		:title="formData.id ? '编辑字典' : '增加字典'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules"  :label-col="labelCol">
			<a-form-item label="上级字典：" name="dictCode">
				<a-input v-model:value="formData.dictCode" placeholder="请输入字典名称" allow-clear disabled="disabled"/>
			</a-form-item>
			<a-form-item label="字典名称：" name="label">
				<a-input v-model:value="formData.label" placeholder="请输入字典名称" allow-clear />
			</a-form-item>
			<a-form-item label="字典值：" name="value">
				<a-input
					v-model:value="formData.value"
					placeholder="请输入字典值"
					allow-clear
				/>
			</a-form-item>
			<a-form-item label="排序" name="sort">
				<a-input v-model:value="formData.sort" type="number" />
			</a-form-item>
			<a-form-item label="状态" name="status">
				<a-switch v-model:checked="formData.status" checkedValue="Y" unCheckedValue="N" checked-children="启用" un-checked-children="停用" />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="dictForm">
	import { required } from '@/utils/formRules'
	import DictApi from '@/api/set/DictApi'
	import DictDataApi from '@/api/set/DictDataApi'

	// 定义emit事件
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const formRef = ref()
	// 表单数据
	let formData = ref({})

	// 打开抽屉
	const onOpen = (record,  dictCode) => {
		visible.value = true
		formData.value = {
			sort: 99,
			status:'N'
		}
		if (dictCode) {
			formData.value.dictCode = dictCode
		}
		if (record) {
			formData.value = Object.assign({}, record)
		} 
	}
	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}
	// 默认要校验的
	const formRules = {
		label: [required('请输入字典名称')],
		value: [required('请输入字典值')],
		sort: [required('请输入排序')]
	}
	// 表单固定label实现
	const labelCol = ref({
		style: {
			width: '100px'
		}
	})
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			DictDataApi.submitForm(formData.value, formData.value.id).then(() => {
				visible.value = false
				emit('successful')
			})
		})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
